<template>
	<view class="ht fdc">
		<map class="wt f1 pr" id="map1" ref="map1" :enable-scroll="value" :enable-zoom="value" :markers="covers" :enable-poi="true" :show-location="true" :longitude="lng" :latitude="lat" @regionchange="regionchange">
			<image class="w4 h4 center" :src="filter.image('sys/location.png')" />
		</map>

		<view v-if="value" class="bgw px6 py2 fac">
			<view @click="$refs.city.show=true">{{filter.region(city_id)}}</view>
			<u-icon name="arrow-down" size="20" class="mx3" @click="$refs.city.show=true" />
			<input class="f1 br8 py3 px6 bg-page" v-model:value="keywords" confirm-type="search" @confirm="search" />
		</view>

		<scroll-view  v-if="value" :scroll-y="true" class="bgw px6 mt2" style="width: auto; max-height: 50vh;">
			<view class="fjb py4" v-for="(item, i) in list" :key="i" @click="choose(i)">
				<view>
					<view>{{item.name}}</view>
					<view class="fs24 c9 mt2">{{item.address}}</view>
				</view>
				<radio :checked="checkedId==i" color="#00B280" />
			</view>
		</scroll-view>

		<City ref="city" v-model:value="cid" />
	</view>
</template>
<script>
import util from '@/utils/util'
import filter from '@/utils/filter'
import map from '@/utils/map'

export default {
	props: {
		value: {
			type: Boolean,
			default: true
		},
		name: {
			type: String,
			default: ''
		},
		city_id: {
			type: [String, Number],
			default: 0
		},
		lng: {
			type: Number,
			default: 0
		},
		lat: {
			type: Number,
			default: 0
		}
	},
	data() {
		return {
			filter: filter,
			list: [],
			keywords: '',
			checkedId: 0,
			covers: [],
			context: null,
			diff: 0
		}
	},
	computed: {
		cid:{
			get(){
				return this.city_id;
			},
			set(val){
				this.$emit('update:city_id', val)
			}
		}
	},
	mounted() {
		this.context = uni.createMapContext('map1', this)
		
		/*
		const that = this
		this.context.getRegion({success(res){
			that.diff = (res.northeast.latitude - res.southwest.latitude) * 0.18
		}})
		*/
	},
	methods: {
		search(){
			map.search(this.keywords, Math.floor(this.city_id/100) * 100).then(pois=>{
				this.list = pois
			})
		},
		choose(i){
			this.checkedId = i
			const item = this.list[i]
			const location = item.location.split(',')
			this.$emit('change', {
				lng: location[0] * 1, 
				lat: location[1] * 1,
				name: item.name,
				dist_id: item.adcode,
				position: Array.isArray(item.address) ? '' : item.address
			})
			this.$emit('update:value', false)
		},
		regionchange(e){
			if(e.type != 'end'){
				return 
			}
			const p = e.detail.centerLocation
			p && map.around({lng: p.longitude, lat: p.latitude}).then(pois=>{
				this.list = pois
			})
		}
	},
	watch: {
		value(newVal, oldVal){
			newVal && !oldVal && map.around({lng:this.lng, lat: this.lat},this.keywords, Math.floor(this.city_id/100) * 100).then(pois=>{
				this.list = pois
			})
		},
		city_id(){
			this.keywords = ''
		}
	}
}
</script>
<style>
.center{
	position: absolute;
	margin:auto;
	left:0;
	top:0;
	right:0;
	bottom:0;
}
</style>
